package com.rub.android.service

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.rub.android.dao.GithubDao
import com.rub.android.widget.RetrofitServiceApi
import com.rub.android.jetpack.model.Repo
import com.rub.android.jetpack.paging.GithubDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

class GitHubService(
    private val githubDao: GithubDao,
    private val serviceApi: RetrofitServiceApi
) {

    suspend fun refreshSearch(perPage:Int,page:Int,keyWord:String) = search(perPage,page,keyWord)

    private suspend fun search(perPage:Int,page:Int,keyWord:String) = withContext(Dispatchers.IO) {
        coroutineScope {
            val response = async { serviceApi.search(perPage,page,keyWord) }
            var await = response.await()
            //本地数据
            //githubDao.search
            await
        }
    }

    /**
     *
     */
     fun getPagingData(keyword:String): Flow<PagingData<Repo>> {
        return Pager(
            config = PagingConfig(PAGE_SIZE),
            pagingSourceFactory = { GithubDataSource(this,keyword) }
        ).flow
    }


    companion object {
        private val TAG = javaClass.simpleName

        private const val PAGE_SIZE = 50
        private var repository: GitHubService? = null

        fun getInstance(dao: GithubDao, api: RetrofitServiceApi): GitHubService {
            if (repository == null) {
                synchronized(GitHubService::class.java) {
                    if (repository == null) {
                        repository = GitHubService(dao, api)
                    }
                }
            }
            return repository!!
        }
    }
}